const {getOR, getUserInfo, getWeappOpenId} = require('../config/wechatLogin')
const redisConfig = require('../config/redisConfig')
const DB = require('../config/sequelize')

const SecretTool = require('../utils/SecretTool')
const BackCode = require('../utils/BackCode')
const WxDataTool = require('../utils/WxDataTool')
const RandomTool = require('../utils/RandomTool')
const CodeEnum = require('../utils/CodeEnum')

const WxLoginService = {
    wechat_insert: (signature, timestamp, nonce, echostr) => {
        let token = 'Jimmy'
        let str = SecretTool.sha1([token, timestamp, nonce].sort().join(''))
        if (str === signature) {
            return echostr
        }
    },
    login: async () => {
        // 获取二维码url
        let {qrcodeUrl, ticket} = await getOR()
        // 将ticket存入redis缓存
        let key = `wechat:ticket:${ticket}`
        redisConfig.set(key, JSON.stringify({isScan: 'no'}), 120)
        return BackCode.buildSuccessAndData({data: {qrcodeUrl, ticket}})
    },
    wechat_message: async (req) => {
        // 处理微信发送的数据
        // 课程版本
        let xmlData = Object.keys(req.body)[0]
        // 正式版本
        // let xmlData = await WxDataTool.getXMLStr(req)
        let objectData = await WxDataTool.getObject(xmlData)
        let lastData = WxDataTool.getLastData(objectData.xml)
        // 根据openid判断是否注册过
        let openidRes = await DB.Account.findAll({where: {openid: lastData.FromUserName}, raw: true})
        //随机生成用户的头像和昵称
        let head_img = RandomTool.randomAvatar()
        let username = RandomTool.randomName()
        let user = null
        // 未注册则插入数据
        if (openidRes.length === 0) {
            let resData = await DB.Account.create({head_img, username, openid: lastData.FromUserName})
            user = {head_img, username, id: resData.toJSON().id}
        } else {
            // 注册过
            user = {head_img: openidRes[0].head_img, username: openidRes[0].username, id: openidRes[0].id}
        }

        // 生成token
        let token = SecretTool.jwtSign(user, '168h')

        // 更新redis状态
        let key = `wechat:ticket:${lastData.Ticket}`
        const existsKey = await redisConfig.exists(key)
        if (existsKey) {
            redisConfig.set(key, JSON.stringify({isScan: 'yes', token}), 120)
        }

        // 返回微信服务器的内容
        let content = ''
        if (lastData.MsgType === 'event') {
            if (lastData.Event === 'SCAN') {
                content = '欢迎回来，讲师微信：JimmyZhu'
            } else if (lastData.Event === 'subscribe') {
                content = '感谢关注，讲师微信：JimmyZhu'
            }

          return `<xml>
        <ToUserName><![CDATA[${lastData.FromUserName}]]></ToUserName>
        <FromUserName><![CDATA[${lastData.ToUserName}]]></FromUserName>
        <CreateTime>${Date.now()}</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[${content}]]></Content>
       </xml>`
        }
    },
    check_scan: async (req) => {
        let {ticket} = req.query
        let key = `wechat:ticket:${ticket}`
        let redisData = JSON.parse(await redisConfig.get(key))
        if (redisData && redisData.isScan === 'yes') {
            let {token} = redisData
            return BackCode.buildSuccessAndData({data: `Bearer ${token}`})
        } else {
            return BackCode.buildResult(CodeEnum.WECHAT_WAIT_SCAN)
        }
    },
    app_login: async (code) => {
        const userInfo = await getUserInfo(code)
        if (userInfo?.openid) {
            let openidRes = await DB.Account.findAll({where: {openid: userInfo.openid}, raw: true})

            let user
            // 未注册则插入数据
            if (openidRes.length === 0) {
                let resData = await DB.Account.create({
                    head_img: userInfo.headimgurl,
                    username: userInfo.nickname,
                    openid: userInfo.openid
                })
                user = {head_img: userInfo.headimgurl, username: userInfo.nickname, id: resData.toJSON().id}
            } else {
                // 注册过
                user = {head_img: openidRes[0].head_img, username: openidRes[0].username, id: openidRes[0].id}
            }

            // 生成token
            let token = SecretTool.jwtSign(user, '168h')
            return BackCode.buildSuccessAndData({data: `Bearer ${token}`})
        }
        return BackCode.buildError({msg: '登录失败'})
    },
    weapp_login: async (code) => {
        const {data} = await getWeappOpenId(code)
        if (data?.openid) {
            let openidRes = await DB.Account.findAll({where: {openid: data.openid}, raw: true})
            let user
            if (openidRes.length === 0) {
                const username = RandomTool.randomName()
                const head_img = RandomTool.randomAvatar()
                // 未注册则插入数据
                let resData = await DB.Account.create({
                    head_img,
                    username,
                    openid: data.openid
                })
                user = {head_img, username, id: resData.toJSON().id}
            } else {
                // 注册过
                user = {head_img: openidRes[0].head_img, username: openidRes[0].username, id: openidRes[0].id}
            }

            // 生成token
            let token = SecretTool.jwtSign(user, '168h')
            return BackCode.buildSuccessAndData({data: `Bearer ${token}`})
        }
        return BackCode.buildError({msg: '登录失败'})
    }
}

module.exports = WxLoginService